package com.beigai.imessage.message.action;

import com.beigai.imessage.common.except.MessageException;
import com.beigai.imessage.message.dto.MRecReq;
import com.beigai.imessage.message.dto.MRecResp;
import com.beigai.imessage.message.dto.MSendReq;
import com.beigai.imessage.message.dto.MSendResp;
import com.beigai.imessage.message.service.MessageService;
import com.beigai.imessage.server.UserSession;
import com.beigai.imessage.session.MemorySessionCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by xxl on 2017/5/16.
 */
@RestController
@RequestMapping("/message")
public class MessageAction {

    @Autowired
    private MessageService messageService;

    /**
     * 发送消息
     *
     * @param mSendReq
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public MSendResp sendMessage(@RequestBody MSendReq mSendReq) {
        try {
            String messageToCode = mSendReq.getMessageToCode();
            boolean online = isOnline(messageToCode);
            MSendResp mSendResp;
            if (online)
                mSendResp = messageService.sendMessageOnline(mSendReq);
            else
                mSendResp = messageService.sendMessageOffline(mSendReq);
            return mSendResp;
        } catch (MessageException e) {
            e.printStackTrace();
            return null;
        }

    }

    @RequestMapping("/receive")
    public MRecResp receiveMessage(@RequestBody MRecReq mRecReq) {
        String messageFromCode = mRecReq.getMessageFromCode();
        boolean online = isOnline(messageFromCode);
        MRecResp mRecResp = null;
        if (online)
            mRecResp = messageService.receiveMessageOnline(mRecReq);
        else
            try {
                mRecResp = messageService.receiveMessageOffline(mRecReq);
            } catch (MessageException e) {
                e.printStackTrace();
            }
        return mRecResp;
    }

    public boolean isOnline(String sessionCode) {
        UserSession session = MemorySessionCache.getInstance().getSession(sessionCode);
        return session == null ? false : true;
    }
}
